package com.novunda.platform.web;

import com.novunda.platform.common.utils.*;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.common.web.modal.Page;
import com.novunda.platform.entities.EmailInfo;
import com.novunda.platform.entities.Office;
import com.novunda.platform.entities.User;
import com.novunda.platform.services.EmailService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 邮件服务Controller
 * Created by YJY on 2016/9/9.
 */
@Controller
@RequestMapping("/email")
public class EmailController extends BaseController {


    /**
     * 邮件服务
     */
    @Autowired
    private EmailService emailService;

    /**
     * 根据id获取邮件服务信息
     *
     * @param id 邮件服务id
     * @return 邮件服务信息
     */
    @RequestMapping("/get")
    @RequiresPermissions("sys:email:view")
    public String get(Long id, Model model,RedirectAttributes redirectAttributes) {
        //判断id是否为空
        if (id != null) {
            EmailInfo emailInfo = emailService.get(id);
            if (emailInfo == null) {
                addMessage(redirectAttributes, "未查到邮件服务器信息");
            } else {
                model.addAttribute("emailInfo", emailInfo);
                return "modules/conf/addEmail";
            }
        } else {
            addMessage(redirectAttributes, "id为空");
        }
        return "redirect:/email";
    }

    /**
     * 邮件服务列表
     *
     * @param request  请求
     * @param response 响应
     * @param model    存放信息，request级别的
     * @return 跳转地址
     */
    @RequestMapping("")
    @RequiresPermissions("sys:email:view")
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<EmailInfo> page = emailService.findEmailInfo(new Page<EmailInfo>(request, response));
        model.addAttribute("page", page);
        return "modules/conf/emailConf";
    }

    /**
     * 创建邮件服务
     *
     * @param emailInfo          邮件信息
     * @param redirectAttributes 用于重定向后能够带参数跳转
     * @param model              存放信息，request级别的
     * @return 重定向路径
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @RequiresPermissions("sys:email:add")
    public String create(@ModelAttribute("emailInfo") EmailInfo emailInfo, HttpServletRequest request, RedirectAttributes redirectAttributes, Model model) {
        //校验参数
        if (beanValidator(model, emailInfo)) {
            //校验邮件格式是否正确
            if (!StringUtil.isEmpty(checkParams(emailInfo, request.getParameter("company.name")))) {
                addMessage(model, checkParams(emailInfo, request.getParameter("company.name")));
                emailInfo.setEmailPassword("");
                return "modules/conf/addEmail";
            }
            // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
            emailInfo.setCompany(new Office(StringKit.toLong(request.getParameter("company.id"))));
            emailInfo.setOffice(new Office(StringKit.toLong(request.getParameter("company.id"))));
            emailInfo.setOrganization(request.getParameter("company.name"));
            EmailInfo email = emailService.createEmail(emailInfo);
            //判断是否是默认邮件服务器
            if (email.isDefaultEmail() || emailService.queryEmailInfo(email.getOrganization()).size() == 1) {
                model.addAttribute("emailInfo", emailService.updateDefaultEmail(email.getId()));
            } else {
                model.addAttribute("emailInfo", email);
            }
            return "redirect:/email";
        } else {
            addMessage(model, "创建邮件服务器失败！");
            emailInfo.setEmailPassword("");
            return "modules/conf/addEmail";
        }
    }

    /**
     * 检查邮件服务器信息
     *
     * @param emailInfo 邮件服务器 信息
     * @return 校验结果
     */
    private String checkParams(EmailInfo emailInfo, String organization) {
        //校验邮件
        if (!RegexValidateUtil.checkEmail(emailInfo.getEmail()) || emailInfo.getEmail().length() > 64) {
            return "邮件格式错误！";
        }
        if (StringUtil.isEmpty(organization)) {
            return "机构不能为空！";
        }
        if (StringUtil.isEmpty(emailInfo.getEmailPassword())) {
            return "邮箱密码不能为空！";
        }
        if (emailInfo.getEmailPassword().length() > 32) {
            return "邮箱密码不能超过32位！";
        }
        if (StringUtil.isEmpty(emailInfo.getServersAddress()) || !StringUtil.isUrl(emailInfo.getServersAddress())
                || emailInfo.getServersAddress().length() > 64) {
            return "邮件服务器地址格式错误！";
        }
        if (emailInfo.getPort() == null) {
            return "端口不能为空！";
        }
        if (StringUtil.isEmpty(emailInfo.getEmailContent())) {
            return "邮件内容不能为空！";
        }
        if (emailInfo.getPort() < 1 || emailInfo.getPort() > 65535) {
            return "端口的范围为1~65535！";
        }
        if (!StringUtil.isEmpty(emailInfo.getEmailRemarks()) && emailInfo.getEmailRemarks().length() > 100) {
            return "邮件备注不能超过100个字符！";
        }
        if (!StringUtil.isEmpty(emailInfo.getEmailTheme()) && emailInfo.getEmailTheme().length() > 100) {
            return "邮件主题不能超过100个字符！";
        }
//        EmailInfo info = emailService.queryEmailInfo(organization, emailInfo.getEmail());
//        //校验是否已存在
//        if (null != info && !info.getId().equals(emailInfo.getId())) {
//            return "此邮件服务器，在该机构下已存在！";
//        }
        return null;
    }

    /**
     * 创建跳转
     *
     * @return 跳转地址
     */
    @RequestMapping(value = {"/createSkip", "/validateEmail"}, method = RequestMethod.GET)
    public String createSkip(Model model) {
        User currentUser = UserUtils.getUser();
        EmailInfo info = new EmailInfo();
        info.setCompany(currentUser.getCompany());
        info.setOffice(currentUser.getOffice());
        model.addAttribute("emailInfo", info);
        return "modules/conf/addEmail";
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createGet(Model model) {
        return createSkip(model);
    }

    @RequestMapping("/update")
    public String updateGet(EmailInfo emailInfo) {
        return "redirect:/email";
    }

    /**
     * 修改邮件服务
     *
     * @param emailInfo          邮件信息
     * @param redirectAttributes 用于重定向后能够带参数跳转
     * @param model              存放信息，request级别的
     * @return 重定向路径
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @RequiresPermissions("sys:email:edit")
    public String update(HttpServletRequest request, EmailInfo emailInfo, RedirectAttributes redirectAttributes, Model model) {
        //校验参数
        if (beanValidator(model, emailInfo)) {
            //校验邮件格式是否正确
            if (!StringUtil.isEmpty(checkParams(emailInfo, request.getParameter("company.name")))) {
                addMessage(model, checkParams(emailInfo, request.getParameter("company.name")));
                return "modules/conf/addEmail";
            }
            // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
            emailInfo.setCompany(new Office(StringKit.toLong(request.getParameter("company.id"))));
            emailInfo.setOffice(new Office(StringKit.toLong(request.getParameter("company.id"))));
            emailInfo.setOrganization(request.getParameter("company.name"));
            emailService.updateEmail(emailInfo);
            return "redirect:/email";
        } else {
            addMessage(model, "修改邮件服务器失败！");
            return "modules/conf/addEmail";
        }
    }

    /**
     * 修改默认邮件
     *
     * @param id 邮件服务器id
     * @return 跳转地址
     */
    @RequestMapping("/ude")
    @RequiresPermissions("sys:email:edit")
    public String updateDefaultEmail(Long id, RedirectAttributes redirectAttributes) {
        //判断id是否为空
        if (id != null) {
            EmailInfo info = emailService.get(id);
            //判断是否为空
            if (info != null) {
                emailService.updateDefaultEmail(id);
            } else {
                addMessage(redirectAttributes,"已被删除!");
            }
        }
        //跳转地址
        return "redirect:/email";
    }

    /**
     * 根据id删除邮件服务
     *
     * @param id                 邮件服务id
     * @param redirectAttributes 用于重定向后能够带参数跳转
     * @return 重定向地址
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:email:delete")
    public String delete(Long id, RedirectAttributes redirectAttributes) {
        //判断id是否为空
        if (id != null) {
            emailService.deleteEmail(id);
        }
        return "redirect:/email";
    }

    /**
     * 验证邮件是否能发送成功
     *
     * @param emailInfo     邮件信息
     * @param model         存放信息，request级别的
     * @param receiverEmail 收件人地址
     */
    @RequestMapping(value = "/validateEmail", method = RequestMethod.POST)
    public String validateEmail(EmailInfo emailInfo, Model model, String receiverEmail, HttpServletRequest request) {
        //校验参数
        if (!StringUtil.isEmpty(checkParams(emailInfo, request.getParameter("company.name")))) {
            addMessage(model, checkParams(emailInfo, request.getParameter("company.name")));
            return "modules/conf/addEmail";
        }
        if (new MailUtil().send(emailInfo, "735379574@qq.com")) {
            addMessage(model, "邮件服务器连接成功!");
            return "modules/conf/addEmail";
        } else {
            addMessage(model, "邮件服务器连接失败!");
            return "modules/conf/addEmail";
        }
    }

}
